from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QLabel, QLineEdit,
    QPushButton, QMessageBox, QHBoxLayout
)
from PyQt5.QtCore import Qt

from rss_reader import DEBUG
from rss_reader.logger import logger
from rss_reader.database.models import User

class LoginDialog(QDialog):
    """用户登录/注册对话框"""

    def __init__(self, session_factory):
        super().__init__()
        self.session = session_factory()  # 主线程的session
        self.authenticated_user = None
        self.setup_ui()

    def setup_ui(self):
        self.setWindowTitle("RSS阅读器 - 登录")
        self.setFixedSize(300, 200)

        layout = QVBoxLayout()

        # 用户名输入
        if DEBUG:
            self.username_input = QLineEdit("admin")
        else:
            self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("用户名")
        layout.addWidget(self.username_input)

        # 密码输入
        if DEBUG:
            self.password_input = QLineEdit("123456")
        else:
            self.password_input.setPlaceholderText("密码")
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.password_input)

        # 按钮布局
        button_layout = QHBoxLayout()

        # 登录按钮
        login_btn = QPushButton("登录")
        login_btn.clicked.connect(self.handle_login)
        button_layout.addWidget(login_btn)

        # 注册按钮
        register_btn = QPushButton("注册")
        register_btn.clicked.connect(self.handle_register)
        button_layout.addWidget(register_btn)

        layout.addLayout(button_layout)
        self.setLayout(layout)

    def handle_login(self):
        """处理登录逻辑"""

        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        if not username or not password:
            logger.warning("登录尝试: 用户名或密码为空")
            QMessageBox.warning(self, "错误", "用户名和密码不能为空")
            return

        try:
            # 查询用户
            user = self.session.query(User).filter_by(username=username).first()
            logger.debug(f"数据库查询结果 - 用户: {user}")  # 调试日志

            if user is None:
                logger.warning(f"登录失败: 用户名 '{username}' 不存在")
                QMessageBox.warning(self, "错误", "用户名或密码不正确")
                return

            # 记录调试信息(不要记录实际密码)
            logger.info(
                f"登录尝试 - 用户: {user.username}, 密码验证: {'成功' if user.password == password else '失败'}")

            if user.password == password:  # 注意: 实际应用中应该使用密码哈希
                self.authenticated_user = user
                self.accept()
            else:
                logger.warning(f"登录失败: 用户 '{username}' 密码不正确")
                QMessageBox.warning(self, "错误", "用户名或密码不正确")

        except Exception as e:
            logger.error(f"登录过程中出错: {str(e)}", exc_info=True)
            QMessageBox.critical(self, "错误", "登录过程中发生错误")

    def handle_register(self):
        """处理注册逻辑"""
        from ..models import User

        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        if not username or not password:
            QMessageBox.warning(self, "错误", "用户名和密码不能为空")
            return

        if len(username) < 3:
            QMessageBox.warning(self, "错误", "用户名至少需要3个字符")
            return

        if len(password) < 6:
            QMessageBox.warning(self, "错误", "密码至少需要6个字符")
            return

        existing = self.session.query(User).filter_by(username=username).first()
        if existing:
            QMessageBox.warning(self, "错误", "用户名已存在")
            return

        try:
            new_user = User(username=username, password=password)
            self.session.add(new_user)
            self.session.commit()

            QMessageBox.information(self, "成功", "注册成功，请登录")
            self.username_input.clear()
            self.password_input.clear()

        except Exception as e:
            self.session.rollback()
            QMessageBox.critical(self, "错误", f"注册失败: {str(e)}")